package 操作zookeeper.zkclientdemo;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * author Veng Su
 * email  1344114844@qq.com
 * date   18-9-16 下午4:24
 */
public class Zkclientdemo {
    public final static String CONNECTSTRING = "192.168.0.201:2181,192.168.0.203:2181,192.168.0.204:2181";

    public static ZkClient geetInstance() {
        return new ZkClient(CONNECTSTRING, 5000);

    }

    @Test
    public void testcreate() {
        ZkClient zkClient = Zkclientdemo.geetInstance();
        zkClient.createEphemeral("/zktest1");

        ACL acl=new ACL(ZooDefs.Perms.CREATE, new Id("digest","root:root"));
        List<ACL> acls=new ArrayList<>();
        acls.add(acl);
        zkClient.createEphemeral("/zktest2",acls);

        zkClient.createEphemeral("/zktest3","324".getBytes(),acls);

        zkClient.create("/zktest","21".getBytes(), CreateMode.PERSISTENT);
        //递归创建
        zkClient.createPersistent("/digui0/digui1/digui2/digui3",true);


        System.out.println("success");
    }

    @Test
    public void testdelete() {
        ZkClient zkClient = Zkclientdemo.geetInstance();

        //普通删除
        zkClient.delete("/zktest");
        zkClient.delete("/zktest1");
        zkClient.delete("/zktest2");
        zkClient.delete("/zktest3");

        //递归删除
        zkClient.deleteRecursive("/digui0");

        boolean is = zkClient.exists("/suveng");
        System.out.println(is);
    }

    @Test
    public void testWatchers() throws InterruptedException {
        ZkClient zkClient = Zkclientdemo.geetInstance();
        zkClient.subscribeDataChanges("/suveng", new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println(s+"->"+o);
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {

            }
        });
        zkClient.writeData("/suveng","suwenguang");
        Thread.sleep(1000);
    }

}
